package com.netbao.controller;



import com.netbao.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author Li Ruihuan
 * @create 2019-07-04 15:32
 */

@Controller
@RequestMapping("/image")
public class ImageController {
    @Value( "${picpath}" )
    private  String UPLOAD_PATH;
    private final ResourceLoader resourceLoader;

    @Autowired
    public ImageController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    //上传图片
    @RequestMapping("/upload")
    @ResponseBody
    public Object uploadImage(@RequestParam("file") MultipartFile file) {
        if(file.isEmpty()){
            return ResponseEntity.status(400).build();
        }
        String fileName = file.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        fileName=fileName.substring(0,fileName .lastIndexOf("."));
        fileName =fileName+ UUID.randomUUID ().toString ().replace ("-","")+suffix;
        System.out.println(fileName);
        File dest = new File(UPLOAD_PATH + "/" + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            if(!dest.exists()) {
                file.transferTo(dest); //保存文件
            }

        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
        return Result.ok (fileName);
    }

    //上传图片
    @RequestMapping("/excel")
    @ResponseBody
    public Object uploadExcel(@RequestParam("file") MultipartFile file) {
        if(file.isEmpty()){
            return ResponseEntity.status(400).build();
        }
        String fileName = file.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        fileName=fileName.substring(0,fileName .lastIndexOf("."));
        fileName =fileName+ UUID.randomUUID ().toString ().replace ("-","")+suffix;
        System.out.println(fileName);
        File dest = new File(UPLOAD_PATH + "/" + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            if(!dest.exists()) {
                file.transferTo(dest); //保存文件
            }

        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
        return Result.ok (fileName);
    }
    //使用流将图片输出
    @GetMapping("/get/{name:.+}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        response.setContentType("image/jpeg;charset=utf-8");
        File file = new File(UPLOAD_PATH + "/" + name);
        if(file.exists()){
            response.setHeader("Content-Disposition", "attachment;fileName=" + name);
        }
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write( Files.readAllBytes( Paths.get(UPLOAD_PATH).resolve(name)));
        outputStream.flush();
        outputStream.close();
    }
    @RequestMapping("/show")
    public ResponseEntity showPhotos(String fileName){

        try {
            // 由于是读取本机的文件，file是一定要加上的， path是在application配置文件中的路径
            return ResponseEntity.ok(resourceLoader.getResource("file:" + UPLOAD_PATH + "/"+fileName));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
}
